package ui

import (
	"gioui.org/layout"
	"gioui.org/widget"
	"gioui.org/widget/material"
)

type RadioButtonGroup struct {
	th      *material.Theme
	enums   *widget.Enum
	buttons []material.RadioButtonStyle

	key                 string
	lastValue, curValue string
}

func NewRadioButtonGroup(th *material.Theme, key string, items []string, selected string) *RadioButtonGroup {
	enum := &widget.Enum{
		Value: selected,
	}
	var buttons []material.RadioButtonStyle
	for _, item := range items {
		btn := material.RadioButton(th, enum, item, item)
		buttons = append(buttons, btn)
	}

	return &RadioButtonGroup{
		th:       th,
		enums:    enum,
		buttons:  buttons,
		key:      key,
		curValue: selected,
	}
}

func (r *RadioButtonGroup) GetSelectedItem() string {
	return r.curValue
}

func (r *RadioButtonGroup) SetSelectItem(item string) {
	if r.curValue != item {
		r.lastValue = r.curValue
		r.curValue = item
		r.enums.Value = item

		BUS.Publish(r.key, *r)
	}
}

func (r *RadioButtonGroup) Layout(gtx layout.Context) layout.Dimensions {
	r.lastValue = r.enums.Value
	changed := r.enums.Update(gtx)
	r.curValue = r.enums.Value

	if changed && r.lastValue != r.curValue {
		BUS.Publish(r.key, *r)
	}

	var children []layout.FlexChild
	for i := range r.buttons {
		children = append(children, layout.Rigid(r.buttons[i].Layout))
	}

	return layout.Flex{
		Axis:    layout.Horizontal,
		Spacing: layout.SpaceEnd,
	}.Layout(gtx, children...)
}
